package org.sample.thread;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Created by alan on 2017/7/9.
 */
public class BlockQueue<E> {

    private List<E> list;

    public BlockQueue() {
        this.list = new LinkedList<E>();
    }

    public void put(E e) {
        synchronized (list) {
            list.add(e);
            list.notify();
        }
    }

    public E take() {
        synchronized (list) {
            while (list.isEmpty()) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (!list.isEmpty())
                return list.remove(0);
            return null;
        }
    }

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        BlockQueue<Long> blockQueue = new BlockQueue<>();
        pool.execute(() -> {
            int count = 10;
            while ((count--) > 0) {
                long millis = ThreadLocalRandom.current().nextLong(200, 500);
                try {
                    Thread.sleep(millis);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                blockQueue.put(millis);
            }
        });

        pool.execute(() -> {
            int count = 10;
            while ((count--) > 0) {
                Long take = blockQueue.take();
                System.out.println(take);
            }
        });

        pool.shutdown();

    }

}